<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>新增配货单--layui后台管理模板 2.0</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="../../layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="../../css/public.css" media="all" />

	<style type="text/css">
		/*设置 layui 表格中单元格内容溢出可见样式*/
		.layui-table-view,
		.layui-table-box,
		.layui-table-body {
			overflow: visible;
		}

		.layui-table-cell {
			height: auto;
			overflow: visible;
		}
	</style>
</head>

<body class="childrenBody" width="60%">
	<form class="layui-form layui-row">

		<input type="hidden" class="layui-input id" name="id">

		<div class="layui-col-md4 layui-col-xs12">
			<div class="layui-form-item">
				<label class="layui-form-label">配货单编号</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input code" lay-verify="required"
						placeholder="请输入编号，格式参考201907150001">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">配货仓库</label>
				<div class="layui-input-block">
					<select name="warehouse_id" class="warehouse_id" lay-filter="warehouse_id">
					</select>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">配货员</label>
				<div class="layui-input-block">
					<select name="employee_id" class="employee_id" lay-filter="employee_id">
					</select>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">备注</label>
				<div class="layui-input-block">
					<textarea placeholder="请输入配货单备注" class="layui-textarea caption"></textarea>
				</div>
			</div>

			<div class="layui-form-item">
				<div class="layui-input-block">
					<button type="button" class="layui-btn" lay-submit="" lay-filter="addDeliverySheet">立即提交</button>
					<button type="reset" class="layui-btn  layui-btn-primary">重置</button>
				</div>
			</div>
		</div>

		<div class="layui-col-md4 layui-col-xs12">
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button type="button" class="layui-btn layui-btn-normal" data-type="addRow" title="添加一种耗材并补全信息">
						<i class="layui-icon">&#xe61f;</i> 添加耗材
					</button>
				</div>
			</div>

			<div class="layui-form-item">
				<div class="layui-input-block">
					<table id="dataTable" lay-filter="dataTable" class="layui-hide"></table>
				</div>
			</div>
		</div>
	</form>

	<script type="text/javascript" src="../../layui/layui.all.js"></script>
	<script type="text/javascript" src="../../js/common.js"></script>
	<script type="text/javascript">
		layui.use(['form', 'layer', 'table'], function () {
			var form = layui.form
			layer = parent.layer === undefined ? layui.layer : top.layer,
				$ = layui.jquery;
			table = layui.table;

			//数据表格实例化			
			var layTableId = "layTable";
			var tableIns = table.render({
				elem: '#dataTable',
				id: layTableId,
				page: true,
				limit: 50,
				data: [],
				totalRow: true,
				width: 605,
				cols: [[
					{ title: '序号', type: 'numbers', width: 50, align: "center" },
					{
						field: 'type', title: '分类', width: 350, templet: function (d) {
							var typeData = eval('(' + window.localStorage.getItem("materialList") + ')');
							var options = renderSelectOptions(typeData, { valueField: "id", textField: "name", selectedValue: d.type }, "耗材分类");
							return '<a lay-event="type"></a><select name="type" lay-filter="type">' + options + '</select>';
						}
					},
					{
						field: 'quantity', title: '数量', edit: 'number', align: "center", width: 100
					},
					{
						field: 'tempId', title: '操作', align: "center", width: 100
						, templet: function (d) {
							return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="' + d.tempId
								+ '"><i class="layui-icon layui-icon-delete"></i>移除</a>';
						}
					}
				]]
			});

			//定义事件集合
			var active = {
				addRow: function () {	//添加一行
					var oldData = table.cache[layTableId];
					var newRow = { tempId: new Date().valueOf(), type: null, quantity: 0 };
					oldData.push(newRow);
					tableIns.reload({
						data: oldData
					});
				},
				updateRow: function (obj) {
					var oldData = table.cache[layTableId];
					for (var i = 0, row; i < oldData.length; i++) {
						row = oldData[i];
						if (row.tempId == obj.tempId) {
							$.extend(oldData[i], obj);
							return;
						}
					}
					tableIns.reload({
						data: oldData
					});
				},
				removeEmptyTableCache: function () {
					var oldData = table.cache[layTableId];
					for (var i = 0, row; i < oldData.length; i++) {
						row = oldData[i];
						if (!row || !row.tempId) {
							oldData.splice(i, 1);    //删除一项
						}
						continue;
					}
					tableIns.reload({
						data: oldData
					});
				},
				save: function () {
					var oldData = table.cache[layTableId];
					console.log(oldData);
					for (var i = 0, row; i < oldData.length; i++) {
						row = oldData[i];
						if (!row.type) {
							layer.msg("检查每一行，请选择分类！", { icon: 5 }); //提示
							return;
						}
					}
					document.getElementById("jsonResult").innerHTML = JSON.stringify(table.cache[layTableId], null, 2);	//使用JSON.stringify() 格式化输出JSON字符串		
				}
			}

			//激活事件
			var activeByType = function (type, arg) {
				if (arguments.length === 2) {
					active[type] ? active[type].call(this, arg) : '';
				} else {
					active[type] ? active[type].call(this) : '';
				}
			}

			//注册按钮事件
			$('.layui-btn[data-type]').on('click', function () {
				var type = $(this).data('type');
				activeByType(type);
			});

			//监听select下拉选中事件
			form.on('select(type)', function (data) {
				var elem = data.elem; //得到select原始DOM对象
				$(elem).prev("a[lay-event='type']").trigger("click");
			});

			//监听工具条
			table.on('tool(dataTable)', function (obj) {
				var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
				switch (event) {
					case "type":
						var select = tr.find("select[name='type']");
						if (select) {
							var selectedVal = select.val();
							if (!selectedVal) {
								layer.tips("请选择一个分类", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
							}
							console.log(selectedVal);
							$.extend(obj.data, { 'type': selectedVal });
							activeByType('updateRow', obj.data);	//更新行记录对象
						}
						break;
					case "state":
						var stateVal = tr.find("input[name='state']").prop('checked') ? 1 : 0;
						$.extend(obj.data, { 'state': stateVal })
						activeByType('updateRow', obj.data);	//更新行记录对象
						break;
					case "del":
						layer.confirm('真的删除行么？', function (index) {
							obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
							layer.close(index);
							activeByType('removeEmptyTableCache');
						});
						break;
				}
			});

			form.on("submit(addDeliverySheet)", function (data) {

				//获取耗材清单
				var material_ids = [];

				var oldData = table.cache[layTableId];
				for (var i = 0, row; i < oldData.length; i++) {
					row = oldData[i];
					if (row.type && row.quantity > 0) {
						material_ids.push(row.type + '-' + row.quantity);
					}
				}

				if (material_ids.length == 0) {
					layer.msg("未选耗材");
					return false;
				}

				$.ajax({
					url: contextPath + '/sys/deliverySheet/save',
					type: 'post',
					dataType: 'json',
					data: {
						id: $(".id").val(),  //配货单ID
						code: $(".code").val(),  //配货单号
						warehouse_id: $(".warehouse_id").val(),  //配货仓库ID
						employee_id: $(".employee_id").val(),  //配货员ID
						caption: $(".caption").val(),  //备注
						material_ids: material_ids.join(',') //耗材清单
					},
					beforeSend: function () {
						i = showLoad();
					},
					success: function (data) {
						closeLoad(i);

						if (data.code == 0) {
							layer.msg("配货单信息保存成功！");
							layer.closeAll("iframe");
							//刷新父页面
							parent.location.reload();
						} else {
							layer.alert(data.msg);
						}
					},
					error: function (data) {
						closeLoad(i);
					}
				});
				return false;
			})

			//初始化数据,提供父窗口调用
			window.initData = function (edit) {
				var warehouseList = eval('(' + window.localStorage.getItem("warehouseList") + ')');
				$(".warehouse_id").append(renderSelectOptions(warehouseList, { valueField: "id", textField: "name", selectedValue: null }, "仓库"));
				var employeeList = eval('(' + window.localStorage.getItem("employeeList") + ')');
				$(".employee_id").append(renderSelectOptions(employeeList, { valueField: "id", textField: "name", selectedValue: null }, "人员"));
				form.render('select');

				//表单赋初值
				if (edit) {
					$(".id").val(edit.id);  //ID
					$(".code").val(edit.code);  //配货单号
					$(".code").addClass("layui-disabled");//禁止修改单号
					$(".warehouse_id").val(edit.warehouseId);  //配货单号
					$(".employee_id").val(edit.employeeId);  //配货单号
					$(".caption").val(edit.caption);  //配货单号
					form.render();

					//耗材清单初始化
					var oldData = table.cache[layTableId];
					var material_ids = edit.materialIds.split(',');
					for (var i = 0, temp; i < material_ids.length; i++) {
						temp = material_ids[i].split('-');
						var newRow = { tempId: new Date().valueOf(), type: temp[0], quantity: temp[1] };
						oldData.push(newRow);
					}
					tableIns.reload({
						data: oldData
					});
				}
			}

		})
	</script>
</body>

</html>